import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:visibility_detector/visibility_detector.dart';
import 'package:get/get.dart';

import 'package:ball_lion/entity/match/zq_match_info_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/sp_utils.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/live/items/gift_effect_view.dart';
import 'package:ball_lion/module/match/detail/zq_match_detail_logic.dart';
import 'package:ball_lion/module/match_detail/live/animate_live_view.dart';
import 'package:ball_lion/module/match_detail/live/match_live_view.dart';
import 'package:ball_lion/module/match_detail/soccer/zq_detail_header.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:ball_lion/widgets/share/share_button.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';

class ZqMatchDetailPage extends StatefulWidget {
  const ZqMatchDetailPage({super.key});

  @override
  State<ZqMatchDetailPage> createState() => _ZqMatchDetailPageState();
}

class _ZqMatchDetailPageState extends State<ZqMatchDetailPage>
    with SingleTickerProviderStateMixin {
  late ZqMatchDetailLogic logic;

  final liveScrollController = ScrollController(initialScrollOffset: 30);

  int id = Get.arguments;

  @override
  void initState() {
    super.initState();
    logic = Get.put(ZqMatchDetailLogic(), tag: '${Get.arguments}');
  }

  @override
  void dispose() {
    logic.scrollC.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return VisibilityDetector(
        key: const Key("soccer match detail"),
        child: GetBuilder<ZqMatchDetailLogic>(
          tag: '$id',
          builder: (_) {
            return Scaffold(
              backgroundColor:
                  logic.isPlayVideo ? Colours.white : Colours.main, //防止中间有一条缝
              body: Stack(
                children: [
                  ExtendedNestedScrollView(
                    pinnedHeaderSliverHeightBuilder: () =>
                        MediaQuery.of(context).padding.top +
                        kToolbarHeight +
                        (logic.isPlayVideo ? 199 : 0),
                    controller: logic.scrollC,
                    physics: const NeverScrollableScrollPhysics(),
                    headerSliverBuilder: (context, innerBoxIsScrolled) => [
                      logic.isPlayVideo ? liveStreamHeader() : matchHeader()
                    ],
                    body: Container(
                      decoration: BoxDecoration(
                        color: Colours.white,
                      ),
                      child: LoadingWidget<bool>(
                        isLoading: logic.info == null,
                        data: false,
                        child: () => Column(
                          children: [
                            SizedBox(
                                height: 40,
                                width: Get.width,
                                child: Styles.tabbar(
                                  controller: logic.tabController,
                                  labelPadding: EdgeInsets.zero,
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceAround,
                                  tabs: List.generate(
                                      logic.tabs.length,
                                      (index) => Row(
                                            children: [
                                              QsText(logic.tabs[index],
                                                  needCenter: true),
                                              if (logic.tabsClick.contains(
                                                      logic.tabs[index]) &&
                                                  SpUtils.getMatchClick(
                                                              logic.tabs[index])
                                                          ?.contains(
                                                              "${logic.matchId}") !=
                                                      true)
                                                Container(
                                                        height: 6,
                                                        width: 6,
                                                        decoration:
                                                            const BoxDecoration(
                                                          shape:
                                                              BoxShape.circle,
                                                          color: Colours.main,
                                                        ))
                                                    .paddingOnly(
                                                        bottom: 10, left: 2)
                                            ],
                                          )),
                                  onTap: (value) {
                                    SpUtils.setMatchClick(
                                        logic.tabs[value], "${logic.matchId}");
                                    Utils.onEvent(
                                        '${logic.liveInfo != null ? "liveroom" : "match_detail"}_tab',
                                        params: {'tab': logic.tabs[value]});
                                    update();
                                  },
                                )),
                            Expanded(
                              child: Container(
                                color: Colours.greyF2F3F7,
                                child: TabBarView(
                                    controller: logic.tabController,
                                    children: List.generate(logic.pages.length,
                                        (index) => logic.pages[index])),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ),
                  const GiftEffect()
                ],
              ),
            );
          },
        ),
        onVisibilityChanged: (info) {
          logic.visible = !info.visibleBounds.isEmpty;
        });
  }

  liveStreamHeader() => SliverAppBar(
      pinned: true,
      expandedHeight: 199,
      leading: Container(),
      backgroundColor: Colours.black,
      systemOverlayStyle:
          const SystemUiOverlayStyle(statusBarIconBrightness: Brightness.light),
      flexibleSpace: FlexibleSpaceBar(
        collapseMode: CollapseMode.pin,
        background: SafeArea(
            child: logic.liveInfo?.vtype == 4
                ? AnimateLiveView(liveInfo: logic.liveInfo, sportsId: 1)
                : MatchLiveView(liveInfo: logic.liveInfo, sportsId: 1)),
      ));

  matchHeader() {
    return SliverAppBar(
      expandedHeight: 199,
      backgroundColor: Colours.transparent,
      systemOverlayStyle:
          const SystemUiOverlayStyle(statusBarIconBrightness: Brightness.light),
      leading: Styles.backButton(),
      titleSpacing: 0,
      title: logic.showTitle
          ? _barTitle()
          : Obx(
              () => Opacity(opacity: logic.opacity.value, child: _barTitle1())),
      titleTextStyle: const TextStyle(color: Colors.white),
      actions: [
        GestureDetector(
          onTap: () async {
            if (User.isFollow(id)) {
              Utils.onEvent("match_detail_collect", params: {'collect': 0});
              User.unFollow(id).then((value) {
                if (User.isFollow(id)) {
                  Toast.text("取消关注失败");
                } else {
                  Toast.text("取消关注成功");
                }
                update();
              });
            } else {
              Utils.onEvent("match_detail_collect", params: {'collect': 1});
              User.follow(id).then((value) {
                if (User.isFollow(id)) {
                  Toast.text("关注成功");
                } else {
                  Toast.text("关注失败");
                }
                update();
              });
            }
          },
          child: Image.asset(
              Utils.getImgPath(
                  User.isFollow(id) ? "collection_red.png" : "collection.png"),
              color: Colours.white,
              width: 24),
        ),
        Container(width: 8),
        ShareButton(
          route: 'tg/matches/zuqiu/fenxi/${logic.matchId}',
          title:
              "${logic.info?.baseInfo?.homeName} vs ${logic.info?.baseInfo?.guestName}",
          content: "${logic.info?.baseInfo?.matchTime}",
          onTap: () => Utils.onEvent("match_detail_share"),
        ),
        Container(width: 16)
      ],
      flexibleSpace: FlexibleSpaceBar(
        collapseMode: CollapseMode.pin,
        background: Obx(() => Opacity(
              opacity: logic.opacity.value,
              child: ZqDetailHeaderWidget(
                info: logic.info,
                logic: logic,
              ),
            )),
      ),
    );
  }

  Widget _barTitle1() {
    final width = MediaQuery.of(context).size.width - 160;
    // final time = logic.info?.state != MatchState.notStart;
    return SizedBox(
      width: width,
      child: GestureDetector(
        onTap: () => Get.toNamed(Routes.leagueDetail,
            parameters: {"type": "0"},
            arguments: logic.info?.baseInfo?.leagueId.toString()),
        child: Column(
          children: [
            QsText(logic.info?.time ?? ""),
            QsText(logic.info?.baseInfo?.nameChs ?? ""),
          ],
        ),
      ),
    );
  }

  Widget _barTitle() {
    String center = "VS";
    Widget? centerW;
    if (logic.info?.state == MatchState.notStart) {
      center = logic.info?.time.split(" ").join("\n") ?? "";
    } else if (logic.info?.state == MatchState.inMatch) {
      center =
          "${logic.info?.homeScore}  ${logic.info?.runningTime ?? logic.info?.baseInfo?.statusName}  ${logic.info?.awayScore}";
      centerW = Row(
        children: [
          Container(
              width: 15,
              height: 16,
              color: Colors.white,
              alignment: Alignment.center,
              child: QsText("${logic.info?.homeScore}",
                  color: Colours.main, fontSize: 12)),
          logic.info?.runningTime != null
              ? Row(
                  children: [
                    QsText(logic.info?.runningTime?.replaceAll("'", "") ?? ""),
                    const QsText("'")
                        .animate(
                          onPlay: (controller) => controller.repeat(),
                        )
                        .fade(duration: 1000.ms)
                  ],
                ).paddingSymmetric(horizontal: 5)
              : QsText(
                      "${logic.info?.runningTime ?? logic.info?.baseInfo?.statusName}")
                  .paddingSymmetric(horizontal: 5),
          Container(
              color: Colors.white,
              width: 15,
              height: 16,
              alignment: Alignment.center,
              child: QsText("${logic.info?.awayScore}",
                  color: Colours.main, fontSize: 12))
        ],
      );
    } else if (logic.info?.state == MatchState.end) {
      center = logic.info?.scoreRate ?? "VS";
    } else {
      center = logic.info?.baseInfo?.statusName ?? "VS";
    }

    return DefaultTextStyle(
      style: const TextStyle(),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Expanded(
            // flex: 3,
            flex: 2,
            child: _titleTeamInfo(logic.info?.baseInfo?.homeName ?? "",
                logic.info?.baseInfo?.homeRanking),
          ),
          Padding(
              padding: const EdgeInsets.symmetric(horizontal: 10),
              child: centerW ??
                  QsText(
                    center,
                    fontSize: 12,
                    height: 1.4,
                    maxLines: 2,
                    textAlign: TextAlign.center,
                  )),
          Expanded(
              flex: 2,
              child: _titleTeamInfo(logic.info?.baseInfo?.guestName ?? "",
                  logic.info?.baseInfo?.guestRanking,
                  left: false)),
        ],
      ),
    );
  }

  _titleTeamInfo(String name, String? rank, {bool left = true}) {
    final tName = Flexible(
      child: QsText(
        name, height: 1.4,
        textAlign: left ? TextAlign.end : TextAlign.start,
        // textDirection: left ? TextDirection.rtl : TextDirection.ltr,
      ),
    );
    // final tRank = rank?.isEmpty ?? true
    //     ? Container()
    //     : QsText("[${rank!}]", style: TextStyle(fontSize: 10));
    var children = [tName];
    if (left) {
      children = children.reversed.toList();
    }
    return Row(
        mainAxisAlignment:
            left ? MainAxisAlignment.end : MainAxisAlignment.start,
        children: children);
  }
}
